<template>
  <div class="salaryChartWrapper">
    <div class="h100" ref="line_echartDom"></div>
  </div>
</template>

<script>
import { chartTop10Salary, getPositionGradeSalary } from "@/api/salary";

export default {
  name: "salaryChart",
  props: {
    regionBarDescAvg: {
      type: String,
      default: "0",
    },
    chartDataIsNotEmpty: {
      type: Boolean,
      default: true,
    },
    hoverValue: {
      type: String,
      default: "0",
    },
    hoverName: {
      type: String,
      default: "",
    },
    chartData: {
      type: Object,
      default: () => ({
        city: ["初级", "中级", "高级", "专家"],
        salary: ["10", "29", "33", "35"],
      }),
    },
  },
  data() {
    return {
      chartData: {},
    };
  },
  computed: {
    isLabelShow() {
      return this.$store.state.chart.isLabelShow;
    },
  },
  created() {},
  mounted() {
    // this.fetchData();
    this.getPositionGradeSalaryFn();
  },
  methods: {
    formatDate(date) {
      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要+1
      const day = ("0" + date.getDate()).slice(-2);
      return `${year}-${month}-${day}`;
    },
    async getPositionGradeSalaryFn() {
      const params = {
        id: this.$route.query.id,
        // 获取今天的日期
        endTime: this.formatDate(new Date()),
        // 获取六个月前的日期
        beginTime: this.formatDate(
          new Date(new Date().setMonth(new Date().getMonth() - 6))
        ),
        regionIds: "100000",
      };
      const res = await getPositionGradeSalary(params);
      console.log("-------------2222------》getPositionGradeSalaryFn", res); 
      if (res.code == 200) {
        if (res.data.length > 0) {
          // this.chartData.city = [];
          this.chartData.city = ["入门", "初级", "中级", "高级"];
          this.chartData.salary = [];
          res.data.forEach((item) => {
            this.chartData.salary.push(item.salaryNum);
            // this.chartData.salary.push((item.salaryNum / 1000).toFixed(2));
          });
        }
        this.init();
      }
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      // params.beginTime = "2023-1-1";
      // params.endTime = "2023-5-1";
      chartTop10Salary(params).then((response) => {
        // console.log("chartTop10Salary--------------->",response.data.list);
        this.$emit("update:regionBarDescAvg", response.data.salaryNum);
        this.chartData = this.handleData(response.data.list);
        if (this.chartData.city.length == 0) {
          this.$emit("update:chartDataIsNotEmpty", false);
        }
        setTimeout(() => {
          this.init();
        }, 500);
      });
    },
    handleData(data) {
      // 降序
      // //console.log("handleData", data);

      // data.sort((a, b) => {
      //   return b.salaryNum - a.salaryNum;
      // });
      let dataArr = {
        city: [],
        salary: [],
      };
      data.forEach((element) => {
        dataArr.city.push(element.salaryRegionName);
        dataArr.salary.push(element.average);
      });

      return dataArr;
    },
    init() {
      if (!this.$refs["line_echartDom"]) return;
      this.myChart = this.$echarts.init(this.$refs["line_echartDom"]);
      let city = this.chartData.city,
        salary = this.chartData.salary;
      let option = {
        xAxis: {
          type: "category",
          data: city,
          name: "(等级)",
          interval: 0,
          // boundaryGap: false,
          axisLabel: {
            formatter(val) {
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split("");
                const index = array.indexOf("市");
                //在下标2处删除0个，加上回车
                array.splice(index, 1);
                return array.join("");
              } else {
                return val;
              }
            },
            color: "#8193B2",
            fontSize: "13px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            lineHeight: 30, //标题行高
            color: "#8193B2",
            verticalAlign: "top", //标题位置
            padding: [0, 0, 0, 0], // 上右下左与原位置距离
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "line",
            lineStyle: {
              color: "#FFFFFF",
              type: "dashed",
            },
          },
          backgroundColor: "#1B78FF",
          borderColor: "#1B78FF",
          textStyle: {
            color: "#fff",
          },
          extraCssText: "white-space: normal;",
          formatter: (params) => {
            const content = params[0];
            const currentValue = parseFloat(content.value);
            const dataIndex = content.dataIndex;
            const allData = salary;

            let growthText = "";
            if (dataIndex > 0) {
              const prevValue = parseFloat(allData[dataIndex - 1]);
              const prevName = city[dataIndex - 1]; // 获取前一个等级的名称
              const growth = currentValue - prevValue;
              const growthRate = ((growth / prevValue) * 100).toFixed(1);
              growthText = `<br/><span style="color: #DFECFC">较</span><span style="color: #FFFFFF; margin: 0 5px">${prevName}</span><span style="color: #DFECFC">${
                growth >= 0 ? "增长:" : "下降:"
              }</span> ${Math.abs(growthRate)}%`;
            }

            return `<div><span style="color: #DFECFC">薪酬平均值</span> ¥${content.value}${growthText}</div>`;
          },
          // position: ["50%", 0],
        },
        grid: {
          right: "50",
          bottom: "50",
          top: "50",
          left: "50",
        },
        yAxis: {
          type: "value",
          // scale: true,
          name: "(薪酬 元)",
          axisLabel: {
            color: "#8193B2",
            fontSize: "12px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            padding: [0, 45, 10, 0], // 上右下左与原位置距离

            color: "#8193B2",
          },
        },
        series: [
          {
            data: salary,
            type: "bar",
            showBackground: false,
            barWidth: "18px",
            label: {
              show: this.isLabelShow,
              position: "top",
            },
            itemStyle: {
              normal: {
                color: this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    //只要修改前四个参数就ok
                    offset: 0,
                    color: "#81B4FF",
                  }, //柱图渐变色
                  {
                    offset: 1,
                    color: "#A3DBFF",
                  },
                ]),
                borderRadius: [4, 4, 0, 0],
              },
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#0068FF", // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#4996FF", // 100% 处的颜色
                    },
                  ],
                  global: false, // 缺省为 false
                },
              },
            },
          },
          {
            data: salary,
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              color: "#1B78FF",
              width: 2,
            },
            itemStyle: {
              color: "#1B78FF",
              borderColor: "#FFFFFF",
              borderWidth: 2,
            },
          },
        ],
      };
      this.myChart.on("mouseover", (params) => {
        this.$emit("update:hoverValue", params.value + "");
        this.$emit("update:hoverName", params.name);
      });
      option && this.myChart.setOption(option);
      window.addEventListener("resize", () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: 1,
      });
      this.$emit("update:hoverValue", this.chartData.salary[1]);
      this.$emit("update:hoverName", this.chartData.city[1]);
    },
  },
};
</script>

<style lang="scss" scoped>
.salaryChartWrapper {
  flex: 1;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  margin-top: 16px;
  color: #222;
  font-weight: bold;
  margin-bottom: 22px;
  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
  .titleTips {
    display: flex;
    align-items: center;
    color: #999999;
    font-size: 14px;
    font-weight: normal;
    margin-left: 8px;
  }
}
.search-container {
  height: 40px;
}
.h100 {
  width: 100%;
  height: 16vw;
  min-width: 615px;
  min-height: 280px;
}
::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  line-height: 22px;
}
::v-deep .el-form-item {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
  padding-top: 6px;
}
</style>
